package com.tcu.part.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tcu.exception.SmartException;
import com.tcu.part.entity.PageInfo;
import com.tcu.part.entity.PartType;
import com.tcu.part.service.IPartTypeService;
import com.tcu.result.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/partType")
public class PartTypeController {

    private IPartTypeService partTypeService;

    @Autowired
    public void setPartTypeService(IPartTypeService partTypeService) {
        this.partTypeService = partTypeService;
    }

    @PostMapping("add")
    public R addPartType(@RequestBody PartType partType){
        if(partType.getId()!=null){
            throw new SmartException(20001,"增加时，id必须为空");
        }
        boolean save = partTypeService.save(partType);
        return save ? R.success() : R.error();
    }
    @DeleteMapping("delete/{id}")
    public R deleteById(@PathVariable String id){
        boolean b = partTypeService.removeById(id);
        return b ? R.success() : R.error();
    }
    @PostMapping("update")
    public R updatePartType(@RequestBody PartType partType){
        if (partType.getId()==null) {
            throw new SmartException(20001,"id为空，无法更新！");
        }
        boolean b = partTypeService.updateById(partType);
        return b ? R.success() : R.error();
    }
    @GetMapping("getOne/{id}")
    public R getOne(@PathVariable String id){
        PartType byId = partTypeService.getById(id);
        return R.success().data("partType", byId);
    }
//    TODO:这里 有无参数
    @PostMapping("list/{current}/{size}")
    public R list(@PathVariable long current,@PathVariable long size){
        Page<PartType> p = new Page<>(current,size);
        Page<PartType> page = partTypeService.page(p);
        List<PartType> records = page.getRecords();
        PageInfo pageInfo = new PageInfo(page.getCurrent(), page.getSize(), page.getTotal(),page.getPages() );
        return R.success().data("list", records).data("pageInfo",pageInfo);
    }
}
